package com.cyt.work.enrollment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.base.util.httpclient.HttpUtil;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.work.enrollment.dao.EnrollmentReleaseDao;
import com.cyt.work.enrollment.dao.EnrollmentRuleDao;
import com.cyt.work.enrollment.model.po.EnrollmentRelease;
import com.cyt.work.enrollment.model.po.EnrollmentRule;
import com.cyt.work.enrollment.model.vo.EnrollmentReleaseVo;
import com.cyt.work.enrollment.model.vo.EnrollmentRuleVo;
import com.cyt.work.enrollment.service.EnrollmentReleaseService;
import com.cyt.work.enrollment.service.EnrollmentRuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 自主招生-招生发布Service层实现类
 *
 * @author caideyong
 * @date 2019-11-22 16:06:41
 */
@Service("enrollmentReleaseService")
public class EnrollmentReleaseServiceImpl extends BaseServiceImpl<EnrollmentRelease> implements EnrollmentReleaseService {

    @Resource
    private EnrollmentReleaseDao enrollmentReleaseDao;
    @Autowired
    private EnrollmentRuleDao enrollmentRuleDao;

    @Autowired
    public void setBaseDao(EnrollmentReleaseDao enrollmentReleaseDao) {
        this.baseDao = enrollmentReleaseDao;
    }

    /**
     * 查询对象集合
     *
     * @param enrollmentReleaseVo 对象
     * @return List 对象集合
     * @author caideyong
     * @date 2019-11-22 16:06:41
     */
    @Override
    public List<EnrollmentRelease> listExample(EnrollmentReleaseVo enrollmentReleaseVo) {
        return enrollmentReleaseDao.getEnrollmentReleaseList(enrollmentReleaseVo);
    }

    /**
     * 分页查询
     *
     * @param enrollmentReleaseVo 接受参数对象
     * @param pageNum             分页数
     * @param pageSize            每页显示条数
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:06:41
     */
    @Override
    public ReturnResult page(EnrollmentReleaseVo enrollmentReleaseVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("create_time desc");
        List<EnrollmentRelease> list = listExample(enrollmentReleaseVo);
        //查询到的数据进行时间判断,当前时间大于或等于结束时间的，修改状态为已结束
        if(list!=null&&list.size()>0){
            Date nowDate=new Date();
            for(EnrollmentRelease en:list){
                if(en.getEndTime().before(nowDate)){
                    en.setState(BaseConstant.ENROLLMENTRELEASE_END);
                    enrollmentReleaseDao.updateByPrimaryKey(en);
                }
            }
        }
        PageInfo<EnrollmentRelease> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param enrollmentReleaseVo 参数接受对象
     * @param sysUser             当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:06:41
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(HttpServletRequest request,EnrollmentReleaseVo enrollmentReleaseVo, SysUser sysUser) {
        //判断主键id是否存在,如果存在就更新,不存在就新建
        if (StringUtils.isBlank(enrollmentReleaseVo.getId())) {
            EnrollmentRelease enrollmentRelease = new EnrollmentRelease(sysUser);
            enrollmentRelease.setId(BaseUtil.uId());
            enrollmentRelease.setName(enrollmentReleaseVo.getName());
            enrollmentRelease.setUnit(enrollmentReleaseVo.getUnit());
            enrollmentRelease.setStartTime(DateUtil.parseDateTime(enrollmentReleaseVo.getStartTime()));
            enrollmentRelease.setEndTime(DateUtil.parseDateTime(enrollmentReleaseVo.getEndTime()));
            enrollmentRelease.setRuleDetail(enrollmentReleaseVo.getRuleDetail());
            enrollmentRelease.setState(enrollmentReleaseVo.getState());//编辑中
            enrollmentRelease.setStuNum(enrollmentReleaseVo.getStuNum());
            enrollmentRelease.setCreator(sysUser.getId());
            enrollmentRelease.setUpdator(sysUser.getId());
            enrollmentRelease.setCreateTime(new Date());
            enrollmentRelease.setApplyId(enrollmentReleaseVo.getApplyId());
            if(StringUtils.isNotBlank(enrollmentReleaseVo.getRuleId())){
                enrollmentRelease.setRuleId(enrollmentReleaseVo.getRuleId());
            }
            //生成二维码和链接
            String qrCode = getQrCode(request, enrollmentRelease.getId(), enrollmentReleaseVo.getApplyId());
            String url = ProProperties.getInstance().getBaseUrl()+"/enrollment/enrollmentstuinfo/getEdit?applyId=" + enrollmentReleaseVo.getApplyId()+"&parentMenuId=enrollmentStuinfoEdit&releaseId="+enrollmentRelease.getId();
            enrollmentRelease.setUrl(url);
            enrollmentRelease.setQrCode(qrCode);
            enrollmentReleaseDao.insert(enrollmentRelease);
            if (StringUtils.isNotBlank(enrollmentReleaseVo.getRuleId())) {
                EnrollmentRule enrollmentRule = enrollmentRuleDao.selectByPrimaryKey(enrollmentReleaseVo.getRuleId());
                enrollmentRule.setUseNum(enrollmentRule.getUseNum()+1);
                enrollmentRuleDao.updateByPrimaryKey(enrollmentRule);
            }
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseDao.selectByPrimaryKey(enrollmentReleaseVo.getId());
            enrollmentRelease.setName(enrollmentReleaseVo.getName());
            enrollmentRelease.setUnit(enrollmentReleaseVo.getUnit());
            enrollmentRelease.setStartTime(DateUtil.parseDateTime(enrollmentReleaseVo.getStartTime()));
            enrollmentRelease.setEndTime(DateUtil.parseDateTime(enrollmentReleaseVo.getEndTime()));
            if(StringUtils.isNotBlank(enrollmentReleaseVo.getRuleId())){
                enrollmentRelease.setRuleId(enrollmentReleaseVo.getRuleId());
            }
            enrollmentRelease.setRuleDetail(enrollmentReleaseVo.getRuleDetail());
            enrollmentRelease.setState(enrollmentReleaseVo.getState());
            enrollmentRelease.setStuNum(enrollmentReleaseVo.getStuNum());
            enrollmentRelease.setUpdator(sysUser.getId());
            enrollmentRelease.setUpdateTime(new Date());
            //生成二维码和链接
            String qrCode = getQrCode(request, enrollmentRelease.getId(), enrollmentReleaseVo.getApplyId());
            String url = ProProperties.getInstance().getBaseUrl()+"/enrollment/enrollmentstuinfo/getEdit?applyId=" + enrollmentReleaseVo.getApplyId()+"&parentMenuId=enrollmentStuinfoEdit&releaseId="+enrollmentRelease.getId();
            enrollmentRelease.setUrl(url);
            enrollmentRelease.setQrCode(qrCode);
            enrollmentReleaseDao.updateByPrimaryKey(enrollmentRelease);
            if(StringUtils.isNotBlank(enrollmentReleaseVo.getUseNum())){
                EnrollmentRule enrollmentRule = enrollmentRuleDao.selectByPrimaryKey(enrollmentReleaseVo.getRuleId());
                enrollmentRule.setUseNum(enrollmentRule.getUseNum()+1);
                enrollmentRuleDao.updateByPrimaryKey(enrollmentRule);
            }
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 生成二维码
     * @author caideyong
     * @date 2019/12/10
     * @params [request, id, applyId]
     * @return [request, id, applyId]
     */
    private String getQrCode(HttpServletRequest request, String id, String applyId) {
        String qrCode = "";
        // String getContextPath = request.getContextPath();
        // String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + getContextPath + "/";
        String realPath = HttpUtil.getRealPath(request);
        String path = realPath + "/upload/enrollment/" + id + ".png";
        File dicFile = new File(realPath + "/upload/enrollment/");
        if  (!dicFile .exists()  && !dicFile .isDirectory()) {
            dicFile .mkdir();
        }
        try {
            File file = new File(path);
            if (file.exists()) {
                // 删除，重新生成
                file.delete();
            }
            OutputStream out = new FileOutputStream(path);
            String url = ProProperties.getInstance().getBaseUrl() + ProProperties.getInstance().getWxOauthURL() + "?applyId=" + applyId +
                    "&path=/phone/enrollment/enrollmentEdit&pathParams=id*" + id;
            new SimpleQrcodeGenerator().generate(url).toStream(out);
            qrCode = "/upload/enrollment/" + id + ".png";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCode;
    }

    /**
     * 结束发布
     *
     * @param enrollmentReleaseVo 传入参数对象
     * @param sysUser             当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019/12/3
     */
    @Override
    public ReturnResult endRelease(EnrollmentReleaseVo enrollmentReleaseVo, SysUser sysUser) {
        if (StringUtils.isNotBlank(enrollmentReleaseVo.getId())) {
            EnrollmentRelease enrollmentRelease = enrollmentReleaseDao.selectByPrimaryKey(enrollmentReleaseVo.getId());
            enrollmentRelease.setState(BaseConstant.ENROLLMENTRELEASE_END);//已结束
            enrollmentReleaseDao.updateByPrimaryKey(enrollmentRelease);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        } else {
            return new ReturnResult(ErrorCode.CODE_1, "结束发布失败，未传入主键！");
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param enrollmentReleaseVo 参数接受对象
     * @param sysUser             当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:06:41
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(EnrollmentReleaseVo enrollmentReleaseVo, SysUser sysUser) {
        //要修改的字段
        EnrollmentRelease enrollmentRelease = new EnrollmentRelease();
        enrollmentRelease.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        enrollmentRelease.setUpdator(sysUser.getId());
        enrollmentRelease.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(EnrollmentRelease.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(enrollmentReleaseVo.getId())) {
            criteria.andIn("id", Arrays.asList(enrollmentReleaseVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        enrollmentReleaseDao.updateByExampleSelective(enrollmentRelease, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param enrollmentReleaseVo 参数接受对象
     * @param sysUser             当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:06:41
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(EnrollmentReleaseVo enrollmentReleaseVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(EnrollmentRelease.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(enrollmentReleaseVo.getId())) {
            criteria.andIn("id", Arrays.asList(enrollmentReleaseVo.getId().split(",")));
        }
        enrollmentReleaseDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }
}